package com.byzk.p2p.front.controller;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.byzk.p2p.admin.base.controller.BaseController;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.borrow.dto.Borrow;
import com.byzk.p2p.admin.borrow.service.BorrowService;
import com.byzk.p2p.admin.borrow.service.ChangeService;
import com.byzk.p2p.admin.borrow.service.TenderService;
import com.byzk.p2p.admin.borrow.vo.BorrowVo;
import com.byzk.p2p.admin.borrow.vo.ChangeVo;
import com.byzk.p2p.admin.borrow.vo.UserTenderVo;
import com.byzk.p2p.admin.fuiou.controller.FuionAccountController;
import com.byzk.p2p.admin.money.service.BorrowPaymentService;
import com.byzk.p2p.admin.money.vo.BorrowPaymentVo;
import com.byzk.p2p.admin.system.service.ResourceService;
import com.byzk.p2p.admin.system.vo.ResourceVo;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserService;

/**
 * 标的相关
 * @author suker.zhou
 *
 */


@Controller
@RequestMapping("/invest")
@Scope("prototype")
public class FrontInvestController extends BaseController {

	@Autowired
	private BorrowService borrowService;
	@Autowired
	private TenderService tenderService;
	@Autowired
	private UserAccountService userAccountService;
	@Autowired
	private UserService userService;
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private BorrowPaymentService borrowPaymentService;
	@Autowired
	private ChangeService changeService ; 
	
	@Autowired
	private FuionAccountController fuionAccountController ; 
	/**
	 * 我要理财页面
	 * @param type      	//标的类型 new--新手专享，borrow--普通标，change--债权转让，默认进入为普通标
	 * @param status    	//债权转让标的状态，默认为所有状态
	 * @param period    	//债权转让期数
	 * @param changeMoney   //债权转让金额 
	 * @param productId 	//产品类型 3.经营贷，4.周转贷，5.供应链贷，6.房E贷,7.车易贷,8.新手专享
	 * @param deadline  	//投资期限
	 * @param percent   	//投资利率
	 * @param index 
	 * @param limit
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public ModelAndView investList(@RequestParam(value="type",required=false,defaultValue="borrow") String type,
			 					   @RequestParam(value="status",required=false,defaultValue="all") String status,
			 					   @RequestParam(value="period",required=false,defaultValue="-1") int period,
			 					   @RequestParam(value="changeMoney",required=false,defaultValue="-1") int changeMoney,
								   @RequestParam(value="productId",required=false,defaultValue="-1") int productId,
								   @RequestParam(value="deadline",required=false,defaultValue="-1") int deadline,
								   @RequestParam(value="paymentMode",required=false,defaultValue="-1") int paymentMode,
								   @RequestParam(value="full",required=false,defaultValue="-1") int full,
								   @RequestParam(value="index",required=false,defaultValue="1") int index,
			   					   @RequestParam(value="limit",required=false,defaultValue="10") int limit,
			                       Model model){
		User user = (User) session.getAttribute("_user");
		user = userService.getById(user == null ?0:user.getId());
		if("change".equals(type)){
			ChangeVo changeVo = new ChangeVo();
			changeVo.setIndex(index);
			changeVo.setChangeMoney(changeMoney);
			changeVo.setPeriod(period);
			changeVo.setStatus(("all".equals(status))?null:status);
			PageInfo<ChangeVo> pageInfo = changeService.listChange(index, limit, changeVo);
			model.addAttribute("changeMoney", changeMoney);
			model.addAttribute("period", period);
			model.addAttribute("status", status);
			model.addAttribute("pageInfo", pageInfo);
			model.addAttribute("total", pageInfo.getTotal());
		}else{
			//普通标
			BorrowVo borrowVo = new BorrowVo();
			//产品id
			borrowVo.setProductId(productId);
			borrowVo.setIndex(index);
			borrowVo.setLimit(limit);
			borrowVo.setDeadline(deadline);
			borrowVo.setPaymentMode(paymentMode);
			borrowVo.setFull(full);
			PageInfo<BorrowVo> pageInfo = borrowService.borrowList(borrowVo);
			model.addAttribute("pageInfo", pageInfo);
			model.addAttribute("productId",productId);
			model.addAttribute("deadline",deadline);
			model.addAttribute("paymentMode",paymentMode);
			model.addAttribute("full",full);
			model.addAttribute("total", pageInfo.getTotal());
		}
		
		model.addAttribute("type", type);
	
		//累计投资人数
		int count = tenderService.getTenderpeopleCount();
		model.addAttribute("count",count);
		//投资总额
		Double amount = tenderService.getAllTenderAmount(null,null);
		model.addAttribute("amount",amount);
		//累计收益
		Double income=tenderService.getAllRecovedInterest();
		model.addAttribute("income",income);
		return new ModelAndView("/front/invest/list");
	}
	
	/**
	 * 借款标详情
	 * @param model
	 * @param id  标id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/detail")
	public String investDetail(Model model,@RequestParam Integer id) throws Exception {
		User user = (User) request.getSession().getAttribute("_user");
		BorrowVo borrowVo = borrowService.detailBorrowVo(id);
		model.addAttribute("borrowVo", borrowVo);
		if(user != null) {
			UserAccount userAccount = userAccountService.getByUserId(user.getId());
			model.addAttribute("userAccount", userAccount);
		}
		if("MONTH".equals(borrowVo.getDateUtil())) {
			Double profit = 10000.00 * borrowVo.getPercent() * 0.01 / 12 * borrowVo.getDeadline();
			model.addAttribute("profit", profit);
		}else if("DAY".equals(borrowVo.getDateUtil())){
			Double profit = 10000.00 * borrowVo.getPercent() * 0.01 / 360 * borrowVo.getDeadline();
			model.addAttribute("profit", profit);
		}
		if(borrowVo != null && borrowVo.getPersonalInfo() != null) {//个人信息图片
			List<ResourceVo> personalInfo = resourceService.getResourcesById(borrowVo.getPersonalInfo());
			model.addAttribute("personalInfo", personalInfo);
		}
		if(borrowVo != null && borrowVo.getCapitalInfo() != null) {//资产信息图片
			List<ResourceVo> capitalInfo = resourceService.getResourcesById(borrowVo.getCapitalInfo());
			model.addAttribute("capitalInfo", capitalInfo);
		}
		List<UserTenderVo> listTender =  tenderService.listUserTenderByBorrowId(id);
		model.addAttribute("listTender", listTender);
		model.addAttribute("paymentModeAll", Borrow.paymentModeAll);
		/** 计算预约倒计时 **/
		if(borrowVo.getTimingShow() != null){
			int second = (int) ((borrowVo.getTimingShow().getTime()-new Date().getTime())/1000L);
			if(second > 0 && second < (60*60*2)) {//两小时以内
				borrowVo.setCountDown(DateUtils.formatSecond(second));
			}
		}
		return "/front/invest/detail1";
	}
	
	/**
	 * 借款记录详细
	 * @param borrowId 借款标id
	 * @param userId 用户id
	 * @return
	 */
	@RequestMapping(value = "/showBorrowDetail",method=RequestMethod.POST)
	public void showBorrowDetail(@RequestParam("borrowId") Integer borrowId,
								@RequestParam("userId") Integer userId) throws Exception {
		BorrowPaymentVo borrowPaymentVo = new BorrowPaymentVo();
		borrowPaymentVo.setUserId(userId);
		borrowPaymentVo.setBorrowId(borrowId);
		List<BorrowPaymentVo> detailList = borrowPaymentService.borrowUserRepayList(borrowPaymentVo);
		printJSON(new JsonMsg(-1, "操作成功", detailList));
	}
	
	/**
	 * 根据paymentId和还款期数检查该期数之前的还款状态
	 * @param paymentId 
	 * @param index 还款当期
	 * @return
	 */
	public boolean checkPayment(Integer borrowId,Integer userId,Integer index){
		if(index==1){
			return true;
		}else{
			if(index>1){
				BorrowPaymentVo borrowPaymentVo = new BorrowPaymentVo();
				borrowPaymentVo.setUserId(userId);
				borrowPaymentVo.setBorrowId(borrowId);
				index=index-1;
				borrowPaymentVo.setPeriodIndex(index);
				List<BorrowPaymentVo> paymentList = borrowPaymentService.borrowUserRepayList(borrowPaymentVo);
				
				if("Y".equals(paymentList.get(0).getStatus())){
					return true;
				}else{
					return false;
				}
			}	
		}
		return false;
	}
	
	/**
	 * 还款
	 * @param pid 还款记录id
	 * @param index 还款期数
	 * @return
	 */
	@RequestMapping(value = "/payment", method = RequestMethod.POST)
	public void payment(@RequestParam("pid") Integer pid) throws Exception {
		User user = (User)session.getAttribute("_user");
		user = userService.getById(user == null ?0:user.getId());
		try {
			if (user == null) {
				printJSON(new JsonMsg(1, "请先登录！"));
				return;
			}
			BorrowPaymentVo borrowPaymentVo = borrowPaymentService.detail(pid);
			if (borrowPaymentVo == null ) {
				printJSON(new JsonMsg(1, "还款失败！未获取到该标的投资者信息！"));
				return ;
			}
			//查询金账户用户可用余额
			UserAccount account = fuionAccountController.getFuionAccountBalance(user);
			if (account == null || account.getBalance() == null || account.getBalance() <= 0d ) {
				printJSON(new JsonMsg(1, "还款失败！未获取到您的金账户信息！"));
				return ;
			}
			
			if (account.getBalance() < borrowPaymentVo.getNotPaymentTotal()) {
				printJSON(new JsonMsg(1, "还款失败！您的金账户可用余额不足,余额为</br>￥"+account.getBalance()+"元, 应还￥"+borrowPaymentVo.getNotPaymentTotal()+"元,请先充值！"));
				return ;
			}
			
			//查询平台用户可用余额
			UserAccount userAccount = userAccountService.getByUserId(user.getId());
			if (userAccount == null || userAccount.getBalance() == null || userAccount.getBalance() <= 0d ) {
				printJSON(new JsonMsg(1, "还款失败！未获取到您的平台账户信息，或者平台账户余额小于等于0！"));
				return ;
			}
			
			if (userAccount.getBalance() < borrowPaymentVo.getNotPaymentTotal()) {
				printJSON(new JsonMsg(1, "还款失败！您的迅泊达可用余额不足,应还</br>￥"+borrowPaymentVo.getNotPaymentTotal()+"元,请先充值！"));
				return ;
			}
			
			if(checkPayment(borrowPaymentVo.getBorrowId(),user.getId(),borrowPaymentVo.getPeriodIndex())){
				printJSON(new JsonMsg(-1, "操作成功！"));
			}else{
				printJSON(new JsonMsg(2, "请按照期数依次还款！"));
			}

		} catch (Exception e) {
			e.printStackTrace();
			printJSON(new JsonMsg(0, "系统异常,请稍后再试！"));
		}
	}
	
	@RequestMapping(value="/borrow/type",method=RequestMethod.POST)
	public void getBorrowById(@RequestParam Integer id) throws Exception{
		Borrow borrow = borrowService.getBorrowById(id);
		if(6 == borrow.getProductId()){
			printJSON(new JsonMsg(1, "新手标！"));
			return;
		}
		if(7 == borrow.getProductId()){
			printJSON(new JsonMsg(2, "白金标！"));
			return;
		}
		printJSON(new JsonMsg(3, "灵通贷！"));
	}
}
